package com.szwistar.common.comm;

import org.apache.mina.core.buffer.IoBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 中控科技指纹门禁通信协议帧
 * @author 张勇
 */
public abstract class ZktFrame implements AsyncFrame {
	protected static Logger LOG = LoggerFactory.getLogger(ZktFrame.class);
	protected static Logger LOGCOMM = LoggerFactory.getLogger("comm");

	public static final byte[] PREFIX = {(byte)0x50, (byte)0x50, (byte)0x82, (byte)0x7D};
	public static final int BASESUM = 0xFC17;

	/**
	 * 求16位累加和(低位在前)
	 * @param bytes
	 * @return
	 */
	public static short sum(IoBuffer buf, int offset, int len) {
		int init = buf.position();
		buf.position(offset);
		if(buf == null || buf.remaining() < len) {
			buf.position(init); return 0;
		}

		int sum = 0;

		while(len >= 2) {
			sum += buf.get() & 0xFF;
			sum += (buf.get()<<8) & 0xFFFF;
			len -= 2;
		}
		if(len > 0) {
			sum += buf.get();
		}

		buf.position(init);
		return (short)(sum & 0xFFFF);
	}

	public short cmd;		// 指令码
	public short sessionId;	// 会话ID
	public short fsn;		// 帧序号
	public byte bytes[];	// 净荷数据(字节)

	@Override
	public int getSequence() { return fsn; }

	public ZktFrame(short cmd, short sessionId, short fsn, byte[] bytes) {
		super();
		this.cmd = cmd;
		this.sessionId = sessionId;
		this.fsn = fsn;
		this.bytes = bytes;
	}
}
